package huy.mmt.gamelathinh.database;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

// DUNG DE tao database sua xoa
public class MyDataHeaper extends SQLiteOpenHelper {
	// Logcat tag
	// Database Version
	private static final int DATABASE_VERSION = 1;

	// Database Name
	private static final String DATABASE_NAME = "gamememory.db";
	private SQLiteDatabase mData = null;
	/**
	 * Ten cac bang trong co so du lieu
	 */

	private static final String TABLE_SCORE = "tb_score";
	private static final String TABLE_IMAGE = "tb_image";
	/**
	 * tEN cac cot trong bang Score
	 * */
	public static final String SCORE_ID = "id";
	public static final String SCORE_NAME = "name_player";
	public static final String SCORE_THEME = "theme"; // string
	public static final String SCORE_SCORE = "score_win";
	/***
	 * tEN CAC COT TRONG bang image_tb VA GIA TRI teen bang
	 * 
	 * @return
	 */
	public static final String IMAGE_ID = "id";
	public static final String IMAGE_NAME = "name_img";
	public static final String IMAGE_THEME = "theme"; // int
	public static final String IMAGE_LEVEL = "level";
	public static final String IMAGE_DIF = "dif";

	/**
	 * Cac cau lenh de ta co the xay dung cac bang
	 * */
	public static final String CREATE_TABLE_SCORE = "CREATE TABLE "
			+ TABLE_SCORE + "(" + SCORE_ID
			+ " INTEGER PRIMARY KEY autoincrement," + SCORE_NAME + " TEXT,"
			+ SCORE_THEME + " INT," + SCORE_SCORE + " INT" + ");";
	public static final String CREATE_TABLE_IMAGE = "CREATE TABLE "
			+ TABLE_IMAGE + "(" + IMAGE_ID
			+ " INTEGER PRIMARY KEY autoincrement," + IMAGE_NAME + " TEXT,"
			+ IMAGE_THEME + " INT," + IMAGE_LEVEL + " INT," + IMAGE_DIF
			+ " INT" + ");";

	public MyDataHeaper(Context context) {
		// TODO Auto-generated constructor stub
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase mData) {
		// TODO Auto-generated method stub
		mData.execSQL(CREATE_TABLE_SCORE);
		mData.execSQL(CREATE_TABLE_IMAGE);

	}

	@Override
	public void onUpgrade(SQLiteDatabase mData, int oldVersion, int newVersion) {
		// on upgrade drop older tables
		mData.execSQL("DROP TABLE IF EXISTS " + TABLE_SCORE);
		onCreate(mData);
		Log.d("cREATE data", "Create tb_score");

		mData.execSQL("DROP TABLE IF EXISTS " + TABLE_IMAGE);
		onCreate(mData);
		Log.d("cREATE data", "Create tb_image");
	}

	/**
	 * Má»Ÿ Database. Náº¿u csdl chÆ°a cÃ³ sáº½ Ä‘Æ°á»£c tá»± táº¡o ra
	 */
	public void openDatabase() {
		mData = this.getWritableDatabase();
	}

	/**
	 * Ä�Ã³ng Database
	 */
	public void closeDatabase() {
		this.close();
	}

	/**
	 * Thá»±c hiá»‡n 1 cÃ¢u lá»‡nh sql
	 * 
	 * @param sql
	 */
	public void execSQL(String sql) {
		this.execSQL(sql);
	}

	/**
	 * Thá»±c hiá»‡n 1 cÃ¢u lá»‡nh query
	 * 
	 * @param query
	 * @return Cursor
	 */
	public Cursor getCursorQuery(String table, String[] columns,
			String selection, String[] selectionArgs, String groupBy,
			String having, String orderBy) {
		return mData.query(table, columns, selection, selectionArgs, groupBy,
				having, orderBy);
	}

	// ===========================================================================
	/**
	 * ThÃªm 1 ngÆ°á»�i vÃ o báº£ng Ä‘iá»ƒm
	 * 
	 * @param mScore
	 */
	public void addScore(ScoreData mScore) {
		if (mData.isOpen()) {
			int id = checkIsInsert(mScore);
			if (id == -10) {
				ContentValues cv = new ContentValues();
				cv.put(SCORE_NAME, mScore.getNamePlayer());
				cv.put(SCORE_SCORE, mScore.getScore());
				cv.put(SCORE_THEME, mScore.getTheme());

				mData.insert(TABLE_SCORE, null, cv);
			} else {
				updateDollar(mScore, id);
			}

			logList(mScore.getTheme());
		}
	}

	/**
	 * cáº­p nháº­t láº¡i tÃªn vÃ  Ä‘iá»ƒm cá»§a ngÆ°á»�i chÆ¡i
	 * 
	 * @param mScore
	 * @param id
	 */
	public void updateDollar(ScoreData mScore, int id) {
		if (mData.isOpen()) {

			ContentValues cv = new ContentValues();
			cv.put(SCORE_NAME, mScore.getNamePlayer());
			cv.put(SCORE_SCORE, mScore.getScore());
			cv.put(SCORE_THEME, mScore.getTheme());
			mData.update(TABLE_SCORE, cv, SCORE_ID + "=" + id, null);
		}
	}

	// ---------------------------------------------------------------------------
	/**
	 * Kiá»ƒm tra xem sá»‘ Ä‘iá»ƒm ngÆ°á»�i chÆ¡i cÃ³ náº±m trong tá»‘p 10 hay khÃ´ng
	 * 
	 * @param name
	 * @return
	 */
	public int checkIsInsert(ScoreData mScore) {
		if (mData.isOpen()) {
			Cursor mCursor = getCursorQuery(TABLE_SCORE, null, SCORE_THEME
					+ "=" + mScore.getTheme(), null, null, null, SCORE_SCORE
					+ " DESC");
			if (mCursor.getCount() < 10) {
				mCursor.close();
				return -10;
			} else {
				mCursor.moveToLast();
				int score = mCursor.getInt(mCursor.getColumnIndex(SCORE_SCORE));
				int id = mCursor.getInt(mCursor.getColumnIndex(SCORE_ID));
				if (mScore.getScore() > score)
					return id;
			}
			mCursor.close();
		}
		return -1;
	}

	// ---------------------------------------------------------------------------
	/**
	 * Láº¥y danh sÃ¡ch ngÆ°á»�i chÆ¡i chiáº¿n tháº¯ng lÆ°u trong csdl
	 * 
	 * @return
	 */
	public ArrayList<ScoreData> getListScore(int theme) {
		ArrayList<ScoreData> listData = new ArrayList<ScoreData>();
		if (mData.isOpen()) {
			Cursor mCursor = getCursorQuery(TABLE_SCORE, null, SCORE_THEME
					+ "=" + theme, null, null, null, SCORE_SCORE + " DESC");
			while (mCursor.moveToNext()) {
				int score = mCursor.getInt(mCursor.getColumnIndex(SCORE_SCORE));
				String name = mCursor.getString(mCursor
						.getColumnIndex(SCORE_NAME));
				int theme1 = mCursor
						.getInt(mCursor.getColumnIndex(SCORE_THEME));
				listData.add(new ScoreData(name, score, theme1));
			}
			mCursor.close();
		}
		return listData;
	}

	// ---------------------------------------------------------------------------
	/**
	 * Log thá»­ dá»¯ liá»‡u
	 * 
	 * @param string
	 */
	public void logList(int theme) {
		ArrayList<ScoreData> listData = getListScore(theme);
		for (int i = 0; i < listData.size(); i++) {
			ScoreData mScore = listData.get(i);

			Log.d("Name- Score", "Name " + mScore.getNamePlayer()
					+ " - Dollar = " + mScore.getScore() + " - Theme = "
					+ mScore.getTheme());
		}
	}

}